<template>
  <div class="post-detail-container">
    <!-- 返回按钮 -->
    <div class="back-section">
      <el-button 
        type="primary" 
        plain 
        icon="el-icon-arrow-left" 
        @click="goBack"
      >
        返回社区
      </el-button>
    </div>

    <!-- 帖子详情 -->
    <el-card class="post-detail-card">
      <div v-if="post" class="post-detail">
        <!-- 帖子标题和标签 -->
        <div class="post-header">
          <h1 class="post-title">{{ post.title }}</h1>
          <el-tag v-if="post.tag" type="info" size="medium">
            {{ post.tag }}
          </el-tag>
        </div>

        <!-- 帖子元信息 -->
        <div class="post-meta">
          <div class="meta-left">
            <span class="meta-item">
              <i class="el-icon-user"></i>
              {{ post.username }}
            </span>
            <span class="meta-item">
              <i class="el-icon-view"></i>
              {{ post.viewCount || 0 }} 浏览
            </span>
            <span class="meta-item">
              <i class="el-icon-chat-line-square"></i>
              {{ currentCommentCount }} 评论
            </span>
            <span class="meta-item">
              <i class="el-icon-star-off"></i>
              {{ post.favoriteCount || 0 }} 收藏
            </span>
          </div>
          <div class="meta-right">
            <div class="time-info">
              <div class="time-item">
                <span class="time-label">发布时间：</span>
                <span>{{ formatDate(post.createdAt) }}</span>
              </div>
              <div class="time-item" v-if="post.updatedAt !== post.createdAt">
                <span class="time-label">更新时间：</span>
                <span>{{ formatDate(post.updatedAt) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 帖子内容 -->
        <div class="post-content">
          <div class="content-text">{{ post.content }}</div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="帖子信息不存在"></el-empty>
    </el-card>

    <!-- 评论区域 -->
    <div class="comments-section">
      <!-- 添加评论 -->
      <el-card class="comment-form-card">
        <div class="comment-form-header">
          <h3>发表评论</h3>
        </div>
        
        <div v-if="userStore.userInfo" class="comment-form">
          <el-input
            v-model="newComment"
            type="textarea"
            placeholder="请输入评论内容..."
            :autosize="{ minRows: 3, maxRows: 6 }"
            maxlength="500"
            show-word-limit
            class="comment-input"
          />
          <div class="comment-actions">
            <el-button 
              type="primary" 
              @click="submitComment"
              :loading="commentSubmitting"
              :disabled="!newComment.trim()"
            >
              发表评论
            </el-button>
          </div>
        </div>
        
        <div v-else class="login-prompt">
          <el-alert
            title="请先登录后再发表评论"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>

      <!-- 评论提示 -->
      <el-card class="comments-info-card">
        <div class="comments-info">
          <el-alert
            title="评论功能说明"
            type="info"
            :closable="false"
          >
            <template #default>
              <p>您可以在此发表评论，评论将会保存到数据库。</p>
              <p>由于当前接口限制，暂时无法显示历史评论列表。</p>
              <p>评论数量会实时更新显示。</p>
            </template>
          </el-alert>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'PostDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    
    // 响应式数据
    const post = ref(null)
    const newComment = ref('')
    const commentSubmitting = ref(false)
    const currentCommentCount = ref(0)
    
    // API 基础URL
    const API_BASE_URL = 'http://localhost:8080'
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 初始化帖子数据
    const initPostData = () => {
      // 从路由参数中获取帖子数据
      if (route.params.postData) {
        try {
          post.value = JSON.parse(route.params.postData)
          currentCommentCount.value = post.value.commentCount || 0
        } catch (error) {
          console.error('解析帖子数据失败:', error)
          ElMessage.error('帖子数据解析失败')
        }
      } else {
        ElMessage.error('未找到帖子数据')
      }
    }
    
    // 提交评论
    const submitComment = async () => {
      if (!newComment.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      
      if (!userStore.userInfo || !userStore.userId) {
        ElMessage.warning('请先登录')
        return
      }

      if (!post.value || !post.value.postId) {
        ElMessage.error('帖子信息不完整')
        return
      }
      
      commentSubmitting.value = true
      try {
        const commentData = {
          postId: Number(post.value.postId),
          userId: Number(userStore.userId),
          content: newComment.value.trim(),
          parentId: null // 一级评论
        }
        
        console.log('提交评论数据:', commentData)
        
        const response = await axios.post(`${API_BASE_URL}/community/comment`, commentData)
        
        ElMessage.success('评论发表成功')
        newComment.value = ''
        
        // 更新评论数量
        currentCommentCount.value += 1
        
      } catch (error) {
        console.error('发表评论失败:', error)
        if (error.response) {
          ElMessage.error(`发表评论失败: ${error.response.data?.message || error.response.statusText}`)
        } else {
          ElMessage.error('发表评论失败，请检查网络连接')
        }
      } finally {
        commentSubmitting.value = false
      }
    }
    
    // 返回社区页面
    const goBack = () => {
      router.push('/community')
    }
    
    // 页面加载时初始化数据
    onMounted(() => {
      // 初始化用户store
      userStore.initialize()
      
      // 初始化帖子数据
      initPostData()
    })
    
    return {
      post,
      newComment,
      commentSubmitting,
      currentCommentCount,
      userStore,
      formatDate,
      submitComment,
      goBack
    }
  }
}
</script>

<style scoped>
.post-detail-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.back-section {
  margin-bottom: 20px;
}

.post-detail-card {
  margin-bottom: 30px;
}

.post-detail {
  padding: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.post-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  line-height: 1.3;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 30px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-left {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.meta-item {
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.meta-item i {
  font-size: 16px;
  color: #409EFF;
}

.meta-right .time-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: flex-end;
}

.time-item {
  font-size: 13px;
  color: #909399;
}

.time-label {
  font-weight: 500;
}

.post-content {
  line-height: 1.8;
  font-size: 16px;
  color: #303133;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.content-text {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.comments-section {
  margin-top: 30px;
}

.comment-form-card,
.comments-info-card {
  margin-bottom: 20px;
}

.comment-form-header {
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.comment-form-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.comment-form {
  padding: 20px;
}

.comment-input {
  margin-bottom: 15px;
}

.comment-actions {
  text-align: right;
}

.login-prompt {
  padding: 20px;
}

.comments-info {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-detail-container {
    padding: 10px;
  }
  
  .post-title {
    font-size: 24px;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .meta-right .time-info {
    align-items: flex-start;
  }
  
  .comment-form {
    padding: 15px;
  }
}
</style>